﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;

namespace TuKu
{
    public class RegexClass
    {
        //private static readonly string ImagePattern = @"((http(s)?://)?)+(((/?)+[\w-.]+(/))*)+[\w-./]+\.+(jpg|jpeg|png|ico|bmp|gif)";
        private List<string> urlList = new List<string>();
        /// <summary>
        /// 取得网址页面中的图片信息
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string doRegex(string url)
        {
            string result = string.Empty;
            WebClient wClient = new WebClient();
            try
            {
                string pageData = Encoding.Default.GetString(wClient.DownloadData(url));
                Match matchPage = Regex.Match(pageData, @"<div(.+)picPage(.+)</div>", RegexOptions.IgnoreCase);//获取分页代码
                Match matchPicpage = Regex.Match(pageData, @"(?<=<div\s*class=""picShow""\s*id=""ps"">)[\s\S]*?(?=</div>)", RegexOptions.IgnoreCase);//获取图片信息

                Regex re = new Regex(@"http://(.+)(.gif|.jpg)", RegexOptions.IgnoreCase);//定义链接
                //Regex re = new Regex(@"http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?", RegexOptions.IgnoreCase);//定义链接
                MatchCollection mc = re.Matches(matchPage.Value);//获取链接
                if (matchPicpage.Success)
                {
                    result = Regex.Match(matchPicpage.Value, @"http://(.+)(.gif|.jpg)", RegexOptions.IgnoreCase).Value;
                    if (result.Length<10)
                    {
                        result = "/style/img/nopicture.jpg";
                    }
                }
            }
            catch
            {
                result = "/style/img/nopicture.jpg";
            }
            
            return result;
        }
        /// <summary>
        /// 获取列表页地址
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string getUrllist(string url)
        {
            string result = string.Empty;
            WebClient wClient = new WebClient();
         
                string pageData = Encoding.Default.GetString(wClient.DownloadData(url));
                Match urldata = Regex.Match(pageData,"<div(.+)picList(.+)</div>",RegexOptions.IgnoreCase);

                if (urldata.Success)
                {
                    Regex re = new Regex(@"<li>(.+)</li>", RegexOptions.IgnoreCase);//定义链接
                    MatchCollection mc = re.Matches(urldata.Value);//获取链接
                    for (int i = 0; i < mc.Count; i++)
                    {
                        mc[i].Value.showBox();
                    }
                }

            return result;
        }

    }
}
